from splinter.browser import Browser
from time import sleep
import traceback
import re
import sys
import httplib2
from urllib import parse
import smtplib


class BrushTicket(object):
    def __init__(self,user_name,password,passengers,from_time,from_station,to_station,number,seat_type,receiver_mobile):

        # 12306账号，密码
        self.user_name = user_name
        self.password = password

        # 乘客姓名
        self.passengers = passengers

        # 起点站，终点站
        self.from_station = from_station
        self.to_station = to_station

        # 乘车日期
        self.from_time = from_time

        # 车次编号
        self.number = number.capitalize()

        # 座位类型所在td位置
        if seat_type == '商务座特等座':
            seat_type_index = 1
            seat_type_value = 9
        elif seat_type == '一等座':
            seat_type_index = 2
            seat_type_value = 'M'
        elif seat_type == '二等座':
            seat_type_index = 3
            seat_type_value = 0
        elif seat_type == '高级软卧':
            seat_type_index = 4
            seat_type_value = 6
        elif seat_type == '软卧':
            seat_type_index = 5
            seat_type_value = 4
        elif seat_type == '动卧':
            seat_type_index = 6
            seat_type_value = 'F'
        elif seat_type == '硬卧':
            seat_type_index = 7
            seat_type_value = 3
        elif seat_type == '软座':
            seat_type_index = 8
            seat_type_value = 2
        elif seat_type == '硬座':
            seat_type_index = 9
            seat_type_value = 1
        elif seat_type == '无座':
            seat_type_index = 10
            seat_type_value = 1
        elif seat_type == '其他':
            seat_type_index = 11
            seat_type_value = 1
        else:
            seat_type_index = 7
            seat_type_value = 3
        self.seat_type_index = seat_type_index
        self.seat_type_value = seat_type_value

        # 通知信息
        self.receiver_mobile = receiver_mobile

        # 主要页面网址        #https://kyfw.12306.cn/otn/resources/login.html
        self.login_url = 'https://kyfw.12306.cn/otn/login/init'
        self.init_my_url = 'https://kyfw.12306.cn/otn/index/initMy12306'
        self.ticket_url = 'https://kyfw.12306.cn/otn/leftTicket/init'
        self.driver_name = 'chrome'

        # 驱动的位置
        self.executable_path = 'C:\\Users\86187\AppData\Local\Programs\Python\Python39\Scripts\chromedriver.exe'
        self.headers = {
           'Cookie': '_passport_session=940fea1c28be4f11a7cf58d3949ac3627383; BIGipServerpassport=820510986.50215.0000; guidesStatus=off; highContrastMode=defaltMode; cursorStatus=off; RAIL_EXPIRATION=1636974211379; RAIL_DEVICEID=MitV2rxhgEprSuMn77t1YGByEIyTnpExKvX4vxyuZSsOiqEjO2imRNueoFHxfFmmlooQqrURh3seMeHWM0iCMbziakWIPTw7_HKBuR0Daj_pHqBKU2wi8lbYSHADn0nVPm1961uTc9kVGkI0sPXG_rcVFFIRKa7f; route=9036359bb8a8a461c164a04f8f50b252; BIGipServerpool_passport=82051594.50215.0000; BIGipServerotn=1105723658.24610.0000',
            'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'
        }
    def do_login(self):
        """登录功能实现，手动识别验证码进行登录"""

        self.driver.visit(self.login_url)
        sleep(1)
        # self.driver.find_by_id('J-userName').input(self.user_name)
        # self.driver.find_by_id('J-password').input(self.password)
        self.driver.fill('J-userName', self.user_name)
        self.driver.fill('J-password', self.password)
        self.driver.find_by_id('loginSub').click()
        print('请输入验证码……')
        while True:
            if self.driver.url != self.init_my_url:
                sleep(1)
            else:
                break


    def start_brush(self):
        """买票功能实现"""
        self.driver = Browser(driver_name=self.driver_name, executable_path=self.executable_path)
        # 浏览器窗口的大小
        self.driver.driver.maximize_window()
        self.do_login()
        self.driver.visit(self.ticket_url)
        try:
            print('开始刷票……')
            # 加载车票查询信息
            self.driver.cookies.add({"_jc_save_fromStation": self.from_station})  # 出发位置
            self.driver.cookies.add({"_jc_save_toStation": self.to_station})  # 目的地
            self.driver.cookies.add({"_jc_save_fromDate": self.from_time})  # 出发时间
            self.driver.reload()
            count = 0
            while self.driver.url.split('?')[0] == self.ticket_url:
                self.driver.find_by_text('查询').click()
                sleep(2)
                count += 1
                print('第%d次点击查询……' % count)
                try:
                    car_no_location = self.driver.find_by_id('queryLeftTable')[0].find_by_text(self.number)[1]
                    current_tr = car_no_location.find_by_xpath("./../../../../..")
                    if current_tr.find_by_tag('td')[self.seat_type_index].text == '--':
                        print('无此座位类型出售，已结束当前刷票，请重新开启！')
                        sys.exit(1)

                    elif current_tr.find_by_tag('td')[self.seat_type_index].text == '无':
                        print('无票，请继续尝试.....')

                    else:
                        # 有票，尝试预订

                        print('刷到票了（余票数：' + str(current_tr.find_by_tag('td')[self.seat_type_index].text) + '），开始尝试预订……')
                        current_tr.find_by_css('td.no-br>a')[0].click()
                        sleep(3)
                        key_value = 1
                        for p in self.passengers:
                            # 选择用户
                            print('开始选择用户……')
                            self.driver.find_by_text(p).last.click()
                            # 选择座位类型
                            print('开始选择席别……')
                            if self.seat_type_value != 0:
                                sleep(1)
                                seat_select = self.driver.find_by_id("seatType_" + str(key_value))[0]
                                seat_select.find_by_xpath("//option[@value='" + str(self.seat_type_value) + "']")[0].click()
                            key_value += 1
                            if p[-1] == ')':
                                self.driver.find_by_id('dialog_xsertcj_ok').click()
                            print('正在提交订单……')
                            self.driver.find_by_id('submitOrder_id').click()
                            # 查看返回结果是否正常
                            submit_false_info = self.driver.find_by_id('orderResultInfo_id')[0].text
                            if submit_false_info != '':
                                print(submit_false_info)
                                self.driver.find_by_id('qr_closeTranforDialog_id').click()
                                sleep(1)
                                self.driver.find_by_id('preStep_id').click()
                                sleep(1)
                                continue
                            print('正在确认订单……')
                            self.driver.find_by_id('qr_submit_id').click()
                            print('预订成功，请及时前往支付……')
                            # 发送通知信息
                            self.send_sms(self.receiver_mobile, '恭喜您，抢到票了，请及时前往12306支付订单！')
                except Exception as error_info:
                    print(error_info)
        except Exception as error_info:
            print(error_info)


    def send_sms(self, mobile, sms_info):
        """发送手机通知短信，用的是-互亿无线-的测试短信"""
        host = "106.ihuyi.com"
        sms_send_uri = "/webservice/sms.php?method=Submit"
        account = "C59782899"
        pass_word = "19d4d9c0796532c7328e8b82e2812655"
        params = parse.urlencode(
            {'account': account, 'password': pass_word,
             'content': sms_info, 'mobile': mobile, 'format': 'json'}
        )
        headers = {"Content-type": "application/x-www-form-urlencoded",
                   "Accept": "text/plain"}
        conn = httplib2.HTTPConnectionWithTimeout(host, port=80, timeout=30)
        conn.request("POST", sms_send_uri, params, headers)
        response = conn.getresponse()
        response_str = response.read()
        conn.close()
        return response_str



if __name__ == '__main__':
    # 12306用户名
    user_name = input('请输入12306用户名：')
    while user_name == '':
        user_name = input('12306用户名不能为空，请重新输入：')
    # 12306登陆密码
    password = input('请输入12306登陆密码：')
    while password == '':
        password = input('12306登陆密码不能为空，请重新输入：')
    # 乘客姓名
    passengers_input = input('请输入乘车人姓名，多人用英文逗号","连接，（例如单人"张三"或者多人"张三,李四"）：')
    passengers = passengers_input.split(",")
    while passengers_input == '' or len(passengers)>4:
        print('乘车人最少1位，最多4位！')
        passengers_input = input('请输入乘车人姓名，多人用英文逗号","连接，（例如单人"张三"或者多人"张三,李四"）：')
        passengers = passengers_input.split(",")
    # 乘车日期
    from_time = input('请输入乘车日期（例如"2018-12-21"):')
    date_pattern = re.compile(r'^\d{4}-\d{2}-\d{2}$')
    while from_time == ''or re.findall(date_pattern,from_time) == []:
        from_time = input('乘车日期不能为空或者时间格式不正确，请重新输入：')

    # 城市cookie字典
    city_list = {'成都': '%u6210%u90FD%2CCDW',
                 '重庆': '%u91CD%u5E86%2CCQW',
                 '北京': '%u5317%u4EAC%2CBJP',
                 '广州': '%u5E7F%u5DDE%2CGZQ',
                 '杭州': '%u676D%u5DDE%2CHZH',
                 '宜昌': '%u5B9C%u660C%2CYCN',
                 '郑州': '%u90D1%u5DDE%2CZZF',
                 '深圳': '%u6DF1%u5733%2CSZQ',
                 '西安': '%u897F%u5B89%2CXAY',
                 '大连': '%u5927%u8FDE%2CDLT',
                 '武汉': '%u6B66%u6C49%2CWHN',
                 '上海': '%u4E0A%u6D77%2CSHH',
                 '南京': '%u5357%u4EAC%2CNJH',
                 '合肥': '%u5408%u80A5%2CHFH'}
    # 出发站
    from_input = input('请输入出发站，需要输入全名（例如“北京”）：')
    while from_input not in city_list.keys():
        from_input = input('出发站不能为空或不支持当前出发站（如有需要，请联系管理员！），请重新输入：')
    from_station = city_list[from_input]
    # 终点站
    to_input = input('请输入终点站，需要输入全名（例如“北京”）：')
    while to_input not in city_list.keys():
        to_input = input('终点站不能为空或不支持当前终点站（如有需要，请联系管理员！），请重新输入：')
    to_station = city_list[to_input]
    # 车次编号
    number = input('请输入车次号（例如“G110”）：')
    while number == '':
        number = input('车次号不能为空，请重新输入：')
    # 座位类型
    seat_type = input('请输入座位类型（例如“软卧”）：')
    while seat_type == '':
        seat_type = input('座位类型不能为空，请重新输入：')
    # 抢票成功，通知该手机号码
    receiver_mobile = input('请预留一个手机号码，方便抢到票后进行通知（例如：18888888888）：')
    mobile_pattern = re.compile(r'^1{1}\d{10}$')
    while receiver_mobile == '' or re.findall(mobile_pattern, receiver_mobile) == []:
        receiver_mobile = input('预留手机号码不能为空或者格式不正确，请重新输入：')
    # 开始抢票
    ticket = BrushTicket(user_name, password, passengers, from_time, from_station, to_station, number, seat_type,receiver_mobile)
    ticket.start_brush()


